/*
 * Copyright (C) 2010 GrayNM <gray-nm@mail.ru>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include "statsfile.h"

extern unsigned long long hwconfig;

ZLTextStatsFileWriter::ZLTextStatsFileWriter(const char* filename):f(NULL) {
	// open file for append in binary mode
	f = fopen(filename,"ab");
	if(f) {
		// write version block
		ZLTSFVersionBlock	oVersion(STATSFILE_CURRENT_VERSION,hwconfig);
		fwrite(&oVersion,1,sizeof(ZLTSFVersionBlock),f);
	} else perror("Cannot open statistics file");
}

ZLTextStatsFileWriter::~ZLTextStatsFileWriter() {
	if(f) {
		// write quit operation
		ZLTSFOperationBlock	oOp(SFO_Exit);
		struct timespec	tm;
		if(clock_gettime(CLOCK_REALTIME,&tm)==0)
			oOp.OperationTime = (clock_t)(tm.tv_sec * 1000 + tm.tv_nsec/1000000);
		else oOp.OperationTime=0;
		fwrite(&oOp,1,sizeof(ZLTSFOperationBlock),f);
		// close file
		fclose(f);
		f = NULL;
	}
}

void ZLTextStatsFileWriter::writePageStats(const ZLPageStats *pagestats) {
	if(!(f && pagestats)) return;
	// write common page info
	unsigned int i,lim;
	ZLTSFPageStatsBlock	oPage(pagestats->getWordCount(),pagestats->getImageCount(),pagestats->getSymbolCount(),lim=pagestats->getLineCount());
	struct timespec	tm;
	if(clock_gettime(CLOCK_REALTIME,&tm)==0)
		oPage.DisplayTime = (clock_t)(tm.tv_sec * 1000 + tm.tv_nsec/1000000);
	else oPage.DisplayTime=0;
	printf("time: %lu.%lu\n",(unsigned long)tm.tv_sec,tm.tv_nsec);
	fwrite(&oPage,1,sizeof(ZLTSFPageStatsBlock),f);
	// write line infos array
	for(i=0;i<lim;++i)
	{
		ZLTSFPageStatsLine	oLine(pagestats->getLine(i));
		fwrite(&oLine,1,sizeof(ZLTSFPageStatsLine),f);
	}
}

void ZLTextStatsFileWriter::writeOperation(ZLStatsFileOperations op) {
	if(!f) return;
	// write operation
	ZLTSFOperationBlock	oOp(op);
	struct timespec	tm;
	if(clock_gettime(CLOCK_REALTIME,&tm)==0)
		oOp.OperationTime = (clock_t)(tm.tv_sec * 1000 + tm.tv_nsec/1000000);
	else oOp.OperationTime=0;
	fwrite(&oOp,1,sizeof(ZLTSFOperationBlock),f);
}
